package com.xyh.service.impl;

import com.xyh.dao.CommentMapper;
import com.xyh.pojo.Comment;
import com.xyh.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;
    @Override
    public List<Comment> getCommentByBlogId(Long blogId) {
        List<Comment> superComments = commentMapper.getCommentByBlogIdAndParentCommentNull(blogId);//顶级评论
        recursivelyGet(superComments);
        return combineChildren(superComments);
    }

    /**
     * 递归迭代，剥洋葱
     * @param superComments 被迭代的对象
     */
    private void recursivelyGet(List<Comment> superComments) {
        for (Comment superComment : superComments) {
            List<Comment> replyComments=commentMapper.getCommentByParentCommentId(superComment.getId());
            if (replyComments.size()>0) {
                superComment.setReplyComments(replyComments);
                recursivelyGet(replyComments);
            }
        }
    }

    /**
     * 合并评论的各层子代到第一级子代集合中
     * @param comments root根节点，blog不为空的对象集合
     * @return 评论集合
     */
    private List<Comment> combineChildren(List<Comment> comments) {
        for (Comment comment : comments) {
            List<Comment> replies = comment.getReplyComments();//获取子评论
            for(Comment reply : replies) {
                recursivelyAdd(reply);//循环迭代，找出子代，存放在tempReplies中
            }
            comment.setReplyComments(tempReplies); //修改顶级节点的reply集合为迭代处理后的集合
            tempReplies = new ArrayList<>();//清除临时存放区
        }
        return comments;
    }

    private List<Comment> tempReplies = new ArrayList<>();//存放迭代找出的所有子代的集合

    /**
     * 递归迭代把所有子级评论添加到顶级评论
     * @param comment 回复的评论
     */
    private void recursivelyAdd(Comment comment) {
        tempReplies.add(comment);//顶节点添加到临时存放集合
        if (comment.getReplyComments().size()>0) {
            List<Comment> replies = comment.getReplyComments();
            for (Comment reply : replies) {
                tempReplies.add(reply);
                if (reply.getReplyComments().size()>0) {
                    recursivelyAdd(reply);
                }
            }
        }
    }
    @Override
    public int save(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if (parentCommentId!=-1) {
            comment.setParentComment(commentMapper.findOne(parentCommentId));
        }else {
            comment.setParentComment(null);
        }
        return commentMapper.save(comment);
    }

    @Override
    public int delete(Serializable id) {
        return 0;
    }
}
